package com.id.supaclean.ui

import android.Manifest
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ImageView
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.os.bundleOf
import androidx.lifecycle.lifecycleScope
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.id.supaclean.R
import com.id.supaclean.dao.KeyDao
import com.id.supaclean.ui.sub.SubActivity
import com.id.supaclean.ui.sub.isEntryAlarmed
import com.id.supaclean.utils.Country
import com.id.supaclean.utils.Events
import com.id.supaclean.utils.InstallChannel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch

class StartActivity : AppCompatActivity() {


    private val launcher =
        registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
            lifecycleScope.launch {
                delay(2000)
                val result = InstallChannel().referrer().map {
                    Events.sendEvent(
                        "InstallReferrer",
                        bundleOf("referrer" to it.first, "isCampaign" to it.second)
                    )
                    it.second
                }.catch {
                    Events.sendEvent("InstallReferrerFailure", "msg" to it.message)
                    emit(false)
                }.first()

                val isInCountry = Country.remoteConfig()
                val isEntryAlarmed = isEntryAlarmed()
                Events.sendEvent(
                    "is_in_alarmed",
                    mapOf(
                        "channel" to result,
                        "isInCountry" to isInCountry,
                        "isEntryAlarmed" to isEntryAlarmed
                    )
                )

                if (isInCountry && isEntryAlarmed && result) {
                    startSubActivity()
                } else {
                    startMainActivity()
                }
            }
        }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestMyPermissions()
        setContentView(R.layout.activity_start)

    }


    private fun startMainActivity() {
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }

    private fun startSubActivity() {
        startActivity(Intent(this, SubActivity::class.java))
        finish()
    }

    private fun requestMyPermissions() {
        launcher.launch(
            arrayOf(
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
            )
        )

    }


}